package com.sgb.merchant.view.activity;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.util.Pair;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.material.tabs.TabLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.link.entity.EventConstant;
import com.sgb.link.entity.MainEvent;
import com.sgb.link.entity.merchant.DemandListEntity;
import com.sgb.link.router.PathMerchant;
import com.sgb.link.view.widget.CustomXTabLayout;
import com.sgb.merchant.R;
import com.sgb.merchant.databinding.MerchantActivitySelfProjectListBinding;
import com.sgb.merchant.view.adapter.SelfDemandListAdapter;
import com.sgb.merchant.viewmodel.SelfDemandListModel;
import com.sgb.net.entity.ListResponse;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: 王彬臣
 * @date: 2021/9/16
 * @Description: 我的投资需求列表
 */
@Route(path = PathMerchant.SelfDemandListActivity)
public class SelfDemandListActivity extends BaseActivity<SelfDemandListModel, MerchantActivitySelfProjectListBinding> {

    private String[] titles = {"全部", "上架", "下架"};
    private boolean mIsLoadMore;
    private boolean mIsHasSearch;
    Map<String, Object> mMap = new HashMap<>();
    SelfDemandListAdapter mAdapter;
    List<DemandListEntity> mList = new ArrayList<>();
    int selectPos;


    @Override
    protected int layoutId() {
        return R.layout.merchant_activity_self_project_list;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(SelfDemandListModel.class);
    }

    @Override
    protected void init() {
        mBinding.setClick(this);
        initAdapter();
        for (String title : titles) {
            mBinding.tabIndustryCategory.addTab(mBinding.tabIndustryCategory.newTab().setText(title));
        }
        mBinding.editSearchRed.setHint("请输入需求标题");
        initEvent();
        initData();
        getData();
    }

    private void initData() {
        mViewModel.ldDel.observe(this, success -> {
            mList.remove(selectPos);
            mAdapter.notifyDataSetChanged();
        });
        mViewModel.liveDataInvestment.observe(this, data -> {
            showProjectList(data);
        });
        mViewModel.ldState.observe(this, success -> {
            DemandListEntity entity = mList.get(selectPos);
            if (entity.getDemandStatus().equals("0")) {
                entity.setDemandStatus("1");
            } else {
                entity.setDemandStatus("0");
            }
            mAdapter.notifyDataSetChanged();
        });

    }

    private void getData() {
        mViewModel.getInvestmentData(mIsLoadMore, mMap);
    }

    private void initEvent() {
        mBinding.tabIndustryCategory.setNormalColor96();
        mBinding.tabIndustryCategory.addOnTabSelectedListener(new CustomXTabLayout.SimpleSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 0) {
                    mMap.remove("demandStatus");
                } else if (tab.getPosition() == 1) {//0 下架 1上架
                    mMap.put("demandStatus", "1");
                } else if (tab.getPosition() == 2) {
                    mMap.put("demandStatus", "0");
                }
                DialogHelper.showProgressDialog(SelfDemandListActivity.this, "加载中...").setCanceledOnTouchOutside(true);
                mIsLoadMore = false;
                getData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        mBinding.ivCloseRed.setOnClickListener(v -> {
            mBinding.editSearchRed.setText("");
            if (mIsHasSearch) {
                DialogHelper.showProgressDialog(this, "搜索中").setCanceledOnTouchOutside(true);
                closeKeybord();
                mMap.remove("demandName");
                mIsLoadMore = false;
                getData();
            }
        });
        mBinding.editSearchRed.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        mBinding.editSearchRed.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                closeKeybord();
                if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    mIsHasSearch = true;
                    if (TextUtils.isEmpty(mBinding.editSearchRed.getText().toString())) {
                        MToast.showToast(SelfDemandListActivity.this, "请输入需求标题");
                        return true;
                    }
                    DialogHelper.showProgressDialog(SelfDemandListActivity.this, "搜索中").setCanceledOnTouchOutside(true);
                    mMap.put("demandName", mBinding.editSearchRed.getText().toString());
                    mIsLoadMore = false;
                    getData();
                }
                return false;
            }
        });
        mBinding.editSearchRed.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    mBinding.ivCloseRed.setVisibility(View.GONE);
                } else {
                    mBinding.ivCloseRed.setVisibility(View.VISIBLE);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void initAdapter() {
        mBinding.displayView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new SelfDemandListAdapter(mList);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ActivityJump.startActivity(PathMerchant.SelfDemandDetailActivity, Pair.create(RouterKey.NO, mList.get(position).getNo()));
            }
        });
        mAdapter.setClickBtnListener(new SelfDemandListAdapter.ClickBtnListener() {


            @Override
            public void putAway(String no, int position) {

                new RoundDialog.Builder(SelfDemandListActivity.this)
                        .title("温馨提示")
                        .content("确定上架该条信息？")
                        .cancel("取消")
                        .confirm("确定")
                        .cancelable(false)
                        .confirmCallback(v12 -> {
                            selectPos = position;
                            mViewModel.updateDemands(no, "1");
                        }).show();

            }

            @Override
            public void dowAway(String no, int position) {
                new RoundDialog.Builder(SelfDemandListActivity.this)
                        .title("温馨提示")
                        .content("下架该信息后，前台将不再继续展示，确定下架？")
                        .cancel("取消")
                        .confirm("确定")
                        .cancelable(false)
                        .confirmCallback(v12 -> {
                            selectPos = position;
                            mViewModel.updateDemands(no, "0");
                        }).show();

            }

            @Override
            public void editClick(String no, int position) {
                ActivityJump.startActivity(PathMerchant.PublishDemandActivity, Pair.create(RouterKey.NO, mList.get(position).getNo()));
            }

            @Override
            public void delClick(String no, int position) {
                new RoundDialog.Builder(SelfDemandListActivity.this)
                        .title("温馨提示")
                        .content("请问是否确认删除？")
                        .cancel("取消")
                        .confirm("确定")
                        .cancelable(false)
                        .confirmCallback(v12 -> {
                            selectPos = position;
                            mViewModel.delProject(no);
                        }).show();


            }
        });
        mAdapter.bindToRecyclerView(mBinding.displayView);
        mBinding.displayView.setAdapter(mAdapter);

        mBinding.refreshLayout.setEnableRefresh(true);
        mBinding.refreshLayout.setEnableLoadMore(true);
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mIsLoadMore = true;
                getData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mIsLoadMore = false;
                getData();
            }
        });
    }

    public void showProjectList(ListResponse<List<DemandListEntity>> entity) {
        mBinding.refreshLayout.finishRefresh();
        mBinding.refreshLayout.finishLoadMore();
        if (!mIsLoadMore) {
            mList.clear();
        }
        if (entity.getList() != null) {
            mList.addAll(entity.getList());
        }
        if (mList.size() == 0) {
            mAdapter.setEmptyView(R.layout.merchant_empty_views);
        }
        mAdapter.notifyDataSetChanged();


        //
        if (entity.getCurrentPage() < entity.getTotalPage()) {
            mIsLoadMore = true;
            mBinding.refreshLayout.resetNoMoreData();
        } else {
            mBinding.refreshLayout.finishLoadMoreWithNoMoreData();
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_back_red) {
            finish();

        } else if (v.getId() == R.id.tv_search) {
            if (mBinding.editSearchRed.getText().toString().equals("")) {
                MToast.showToast(this, "请输入需求标题");
                return;
            }
            DialogHelper.showProgressDialog(this, "搜索中").setCanceledOnTouchOutside(true);
            mIsHasSearch = true;
            mMap.put("demandName", mBinding.editSearchRed.getText().toString());
            closeKeybord();
            mIsLoadMore = false;
            getData();
        } else if (v.getId() == R.id.tv_publish) {
            ActivityJump.startActivity(PathMerchant.PublishDemandActivity);
        }
    }

    @Override
    public boolean isUseEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MainEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_MERCHANT_SELF_REFRESH_DEMANDS) {
            mIsLoadMore = false;
            getData();
        }
    }
}
